package com.lagou.hbase.hbaseclient;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FriendTest {
    Configuration conf = null;
    Connection conn = null;
    Admin admin = null;
    //初始化链接
    @Before
    public void init() throws IOException {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","linux121,linux122");
        conf.set("hbase.zookeeper.property.clientPort","2181");
        conn = ConnectionFactory.createConnection(conf);
    }

    //创建用户关系表
    @Test
    public void CreateFriendTable() throws IOException {
        admin = conn.getAdmin();
        HTableDescriptor friendship = new HTableDescriptor(TableName.valueOf("friendship"));
        friendship.addFamily(new HColumnDescriptor("friends"));
        admin.createTable(friendship);
        System.out.println("friendship表创建成功！");
    }

    //向friendship表插入数据
    @Test
    public void putData() throws IOException {
        Table friendship = conn.getTable(TableName.valueOf("friendship"));
        String rowkey = "uid";
        //批量插入数据
        List<Put> list = new ArrayList<Put>();
        for(int i=1;i<=6;i++){
            Put put = new Put(Bytes.toBytes(rowkey+i));
            put.addColumn(Bytes.toBytes("friends"),Bytes.toBytes(rowkey+(7-i)),Bytes.toBytes(rowkey+(7-i)));
            list.add(put);
        }
        friendship.put(list);
        friendship.close();
        System.out.println("批量插入成功");
    }

}
